package com.XDApp.xdbase.activitys;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.BaseActivity;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.ProgressHUD;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.xinsilu.R;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 *	 预订
 */
public class ReservationActivity extends BaseActivity implements OnClickListener {

	private static final int REQUEST_RILI = 0;
	private static final String TAG = "预订";

	public static final int TYPE_TICKET = 0;
	public static final int TYPE_PRODUCT = 1;

	/** 提交*/
	private Button btnSubmit;
	/** 增加*/
	private Button btnAdd;
	/** 减少*/
	private Button btnReduce;
	/** 日历*/
	private Button btnRili;
	/** 联系人*/
	private Button btnContact;
	/** 信息*/
	private TextView tvContent;
	/** 出行时间*/
	private TextView tvDate;
	/** 应付金额*/
	private TextView tvPay;
	/** 价格*/
	private TextView tvPrice;
	/** 票数*/
	private TextView tvNum;
	/** 预订说明*/
	private TextView tvExplainYd;
	/** 费用说明*/
	private TextView tvExplainFei;
	/** 退票说明*/
	private TextView tvExplainTp;
	/** 说明*/
	private TextView tvExplain;
	/** 姓名*/
	private EditText etName;
	/** 电话*/
	private EditText etPhone;
	/** 地址*/
	private EditText etAddr;
	/** 用户须知*/
	private CheckBox cb;

	private ImageButton ibMore;

	private int currentNum = 1;
	private int price = 0;
	private int totalPrice = 0;

	private int currentExplain = 0;
	/**　游玩时间*/
	private String orderPlayTime = "";
	/**　下单时间*/
	private String orderTime = "";
	/**　订单门票的价格*/
	private String orderPrice = "0";
	/**　订单门票的张数*/
	private String orderNum = "";
	/**　订单门票的用户名*/
	private String orderUserName = "";
	/**　订单门票的电话*/
	private String orderPhone = "";
	/**　订单门票的地址*/
	private String orderAdress = "";
	/**　门票id*/
	private String mpId = "";
	/**　终端类型*/
	private final String osType = "ANDROID";
	/**　用户id*/
	private String userId = "";
	/**　订单的标题*/
	private String orderName = "";

	private int type = 0;

	private SharedPreferences sp;

	private RelativeLayout rlRq;
	private RelativeLayout rladdr;
	private View vRq;
	private TextView tvTicketName;
	private TextView tv_qprxx;

	private View v1, v2, v3;
	// 标题控件
	private ImageView back;
	private TextView title;

	@Override
	protected void initViews() {

		setContentView(R.layout.activity_reservation);

		type = getIntent().getIntExtra("type", 0);
		orderPrice = getIntent().getStringExtra("price");
		orderName = getIntent().getStringExtra("title");
		mpId = getIntent().getStringExtra("id");

		price = Integer.parseInt(orderPrice);

		sp = getSharedPreferences(MainActivity.class.getSimpleName(), MODE_PRIVATE);
		userId = sp.getString("userID", "");

		// 标题控件
		back = (ImageView) findViewById(R.id.title_back);
		title = (TextView) findViewById(R.id.title_text);
		title.setText("预订");

		btnSubmit = (Button) findViewById(R.id.btn_submit);
		btnAdd = (Button) findViewById(R.id.btn_add);
		btnReduce = (Button) findViewById(R.id.btn_reduce);
		btnRili = (Button) findViewById(R.id.btn_rili);
		btnContact = (Button) findViewById(R.id.btn_contacts);
		ibMore = (ImageButton) findViewById(R.id.ib_more);

		tvContent = (TextView) findViewById(R.id.tv_content);
		tvNum = (TextView) findViewById(R.id.tv_num);
		tvPay = (TextView) findViewById(R.id.tv_pay);
		tvExplainYd = (TextView) findViewById(R.id.tv_explain_yd);
		tvExplainFei = (TextView) findViewById(R.id.tv_explain_fei);
		tvExplainTp = (TextView) findViewById(R.id.tv_explain_tp);
		tvExplain = (TextView) findViewById(R.id.tv_explain);
		tvDate = (TextView) findViewById(R.id.tv_time);

		cb = (CheckBox) findViewById(R.id.cb_pact);

		tvPrice = (TextView) findViewById(R.id.tv_price);

		etName = (EditText) findViewById(R.id.et_name);
		etPhone = (EditText) findViewById(R.id.et_tel);
		etAddr = (EditText) findViewById(R.id.et_addr);

		rlRq = (RelativeLayout) findViewById(R.id.rl_rq);
		rladdr = (RelativeLayout) findViewById(R.id.rl_addr);
		vRq = findViewById(R.id.v_rq);
		v1 = findViewById(R.id.view_1);
		v2 = findViewById(R.id.view_2);
		v3 = findViewById(R.id.view_3);
		tvTicketName = (TextView) findViewById(R.id.tvTicketName);
		tv_qprxx = (TextView) findViewById(R.id.tv_qprxx);

		if (type == TYPE_PRODUCT) {
			rlRq.setVisibility(View.GONE);
			vRq.setVisibility(View.GONE);
			tvTicketName.setText("特产信息");
			tvExplainTp.setText("退货说明");
			tv_qprxx.setText("收货人信息");

		} else if (type == TYPE_TICKET) {
			rladdr.setVisibility(View.GONE);
			tvTicketName.setText("门票信息");
		}

		tvContent.setText(orderName);
		updetePiece();

	}

	@SuppressLint("SimpleDateFormat")
	@Override
	protected void initEvents() {
		back.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
		btnReduce.setOnClickListener(this);
		btnRili.setOnClickListener(this);
		btnContact.setOnClickListener(this);
		tvExplainYd.setOnClickListener(this);
		tvExplainFei.setOnClickListener(this);
		tvExplainTp.setOnClickListener(this);
		ibMore.setOnClickListener(this);

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// orderPlayTime = format.format(new Date());
		orderPlayTime = "请选择日期";
		tvDate.setText(orderPlayTime);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);

		if (requestCode == REQUEST_RILI) {
			if (resultCode == RESULT_OK) {
				orderPlayTime = intent.getStringExtra("date");
				tvDate.setText(orderPlayTime);
			}
		}
	}

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_submit:
			boolean isCheck = cb.isChecked();
			if (!isCheck) {
				showShortToast("请先阅读用户须知并同意。");
				return;
			}

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			orderTime = format.format(new Date());
			orderNum = currentNum + "";

			orderUserName = etName.getText().toString();
			if (TextUtils.isEmpty(orderUserName)) {
				showShortToast("姓名不能为空");
				return;
			}
			orderPhone = etPhone.getText().toString();
			if (TextUtils.isEmpty(orderPhone)) {
				showShortToast("电话不能为空");
				return;
			}

			if (!CommonUtil.isMobilePhone(orderPhone)) {
				showShortToast("手机号不合法");
				return;
			}

			if (currentNum == 0) {
				showShortToast("门票数量不能等于0");
				return;
			}

			orderAdress = etPhone.getText().toString();

			submit();

			break;
		case R.id.title_back:
			finish();
			break;
		case R.id.btn_add:

			currentNum++;
			updetePiece();

			break;
		case R.id.btn_reduce:

			if (currentNum > 0) {
				currentNum--;
				updetePiece();
			}

			break;
		case R.id.btn_rili:
			// showShortToast("日历");
			intent = new Intent(ReservationActivity.this, CalendarActivity.class);
			startActivityForResult(intent, REQUEST_RILI);
			// startActivity(intent);
			break;
		case R.id.btn_contacts:
//			showShortToast("联系人");
			break;
		case R.id.tv_explain_yd:
			if (currentExplain != 0) {
				currentExplain = 0;
				updateExplain();
			}

			break;
		case R.id.tv_explain_fei:
			if (currentExplain != 1) {
				currentExplain = 1;
				updateExplain();
			}
			break;
		case R.id.tv_explain_tp:
			if (currentExplain != 2) {
				currentExplain = 2;
				updateExplain();
			}
			break;
		case R.id.ib_more:
			tvExplain.setMaxLines(100);
			ibMore.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}

	private void submit() {
		// intent = new Intent(ReservationActivity.this,
		// OrderDetailActivity.class);
		// intent.putExtra("pay", OrderDetailActivity.UNPAID);
		// // intent.putExtra("pay", OrderDetailActivity.PAID);
		// startActivity(intent);
		// finish();
		if (CommonUtil.checkNetState(mContext)) {
			String url = "";
			RequestParams params = new RequestParams();
			params.put("orderName", orderName);
			if (type == TYPE_PRODUCT) {
				params.put("orderTime", orderTime);
				params.put("adress", orderAdress);
				url = xdConfig.GET_RESERVESPECIAL;
			} else if (type == TYPE_TICKET) {
				params.put("orderPlayTime", orderPlayTime);
				url = xdConfig.GET_RESERVETICKET;
			}
			params.put("orderPrice", orderPrice);
			params.put("orderNum", orderNum);
			params.put("orderUserName", orderUserName);
			params.put("orderPhone", orderPhone);
			params.put("mpId", mpId);
			params.put("ostype", osType);
			params.put("userID", userId);

			final ProgressHUD ProgressDialog = ProgressHUD.show(mContext, "正在加载...", true, true, null);
			XDHttpClient.post(url, params, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, String content) {

					if (null != ProgressDialog && ProgressDialog.isShowing())
						ProgressDialog.dismiss();
					Log.i(TAG, content);
					JSONObject obj;
					try {
						obj = new JSONObject(content);
						String state = obj.getString("state");
						String msg = obj.getString("msg");

						// 判断返回数据是否正确
						if (state.equals("1")) {
							JSONObject objDate = obj.getJSONObject("data");
							String orderId = objDate.getString("orderId");
							Intent intent = new Intent(ReservationActivity.this, OrderDetailActivity.class);
//							intent.putExtra("payType", OrderDetailActivity.UNPAID);
							intent.putExtra("type", type);
//							intent.putExtra("totalPrice", totalPrice + "");
//							intent.putExtra("orderUserName", orderUserName);
//							intent.putExtra("orderPhone", orderPhone);
//							intent.putExtra("orderName", orderName);
							intent.putExtra("orderId", orderId);
//							intent.putExtra("mpId", mpId);
//							intent.putExtra("orderTime", orderTime);
//							intent.putExtra("orderPlayTime", orderPlayTime);
//							intent.putExtra("orderAdress", orderAdress);
							startActivity(intent);
							finish();
							// 关闭掉这个Activity
						} else {
							CommonUtil.showToast(mContext, msg);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					if (null != ProgressDialog && ProgressDialog.isShowing()) {
						ProgressDialog.dismiss();
					}
					super.onFailure(arg0, arg1);
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();

				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}

	}

	@SuppressLint("NewApi")
	private void updateExplain() {

		int green = getResources().getColor(R.color.text_color);
		int black = getResources().getColor(R.color.black);

		if (currentExplain == 0) {
			tvExplainYd.setTextColor(green);
			tvExplainTp.setTextColor(black);
			tvExplainFei.setTextColor(black);

			v1.setBackground(getResources().getDrawable(R.drawable.bg_sj));
			v2.setBackground(getResources().getDrawable(R.drawable.bg_title_default));
			v3.setBackground(getResources().getDrawable(R.drawable.bg_title_default));

		} else if (currentExplain == 1) {
			tvExplainYd.setTextColor(black);
			tvExplainTp.setTextColor(black);
			tvExplainFei.setTextColor(green);

			v1.setBackground(getResources().getDrawable(R.drawable.bg_title_default));
			v2.setBackground(getResources().getDrawable(R.drawable.bg_sj));
			v3.setBackground(getResources().getDrawable(R.drawable.bg_title_default));
		} else if (currentExplain == 2) {
			tvExplainYd.setTextColor(black);
			tvExplainTp.setTextColor(green);
			tvExplainFei.setTextColor(black);

			v1.setBackground(getResources().getDrawable(R.drawable.bg_title_default));
			v2.setBackground(getResources().getDrawable(R.drawable.bg_title_default));
			v3.setBackground(getResources().getDrawable(R.drawable.bg_sj));
		}

	}

	/** 改变支付金额*/
	private void updetePiece() {
		tvNum.setText("" + currentNum);
		totalPrice = currentNum * price;
		tvPay.setText("" + totalPrice);
		tvPrice.setText("" + price);
	}

}
